#!/bin/bash

MAINLINE_DIR=/Volumes/Coding/linux-torvalds
OH_DIR=/Volumes/Coding/kernel_linux_5.10

# 用法说明
usage() {
    echo "用法: $0 <issue> <cve> <subject>"
    exit 1
}

# 检查参数数量
if [ "$#" -ne 3 ]; then
    usage
fi

ISSUE=$1
CVE=$2
SUBJECT="$3"

contains_keyword() {
    local string="$1"
    local keyword="$2"
    
    if [[ "$string" == *"$keyword"* ]]; then
        return 0  # 包含，返回成功
    else
        return 1  # 不包含，返回失败
    fi
}

get_subject_hash() {
    local subject="$1"
    ./analyze.sh $MAINLINE_DIR "$subject" | awk -F ':' '{print $3}' | awk -F " " '{print $1}'
}

FOUND_COMMIT=$(./analyze.sh $OH_DIR "$SUBJECT")
echo $FOUND_COMMIT

MASTER_CACHE=.git-log-oneline-master.cache
RELEASE_CACHE=.git-log-oneline-OpenHarmony-5.0.3-Release.cache

NEED_FIX=0

if contains_keyword "$FOUND_COMMIT" "$MASTER_CACHE"; then
    echo "fixed: master"
else
    echo "need to fix: master"
    NEED_FIX=1
fi

if contains_keyword "$FOUND_COMMIT" "$RELEASE_CACHE"; then
    echo "fixed: 503"
else
    echo "need to fix: 503"
    NEED_FIX=1
fi

if [ $NEED_FIX -eq 1 ]; then
    echo "Generating patch..."
    comhash=$(get_subject_hash "$SUBJECT")
    ./commit.py $comhash $ISSUE $CVE
fi

